﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Xml;
using WebFormDesigner.Business;

namespace WebFormDesigner.Controllers
{
    public class FormDesignController : Controller
    {
        //
        // GET: /FormDesign/
        [HttpPost]
        public JsonResult SaveCRFHtm(string parFormId, string parFormHtm)
        {
            DataWrapper ret = new DataWrapper();
            try
            {
                string basePath = Server.MapPath("~/FormModule");
                string filePath = basePath + "\\" + parFormId + ".htm";

                parFormHtm = HttpUtility.UrlDecode(parFormHtm);

                System.IO.StreamWriter file1 = new System.IO.StreamWriter(filePath, false); //文件已覆盖方式添加内容
                file1.Write(parFormHtm);                                                              //保存数据到文件

                file1.Close();                                                                  //关闭文件
                file1.Dispose();

                //更新Form数据，IsCreate为1
                if (CommonTools.OleDbConn.State != ConnectionState.Open)
                {
                    CommonTools.OleDbConn.Open();
                }
                OleDbCommand cmd = new OleDbCommand();
                cmd.Connection = CommonTools.OleDbConn;

                cmd.CommandText = "update Form set IsCreate = 1 where ID=" + parFormId;
                cmd.ExecuteNonQuery();
                CommonTools.OleDbConn.Close();

                ret.Result = true;
            }
            catch (Exception ex) {
                ret.Message = ex.Message;
                if (CommonTools.OleDbConn.State != ConnectionState.Closed){
                    CommonTools.OleDbConn.Close();
                }
            }

            return Json(ret);
        }

        public JsonResult QueryByFuncType(string FuncType) {
            DataWrapper ret = new DataWrapper();
            try
            {
                if (CommonTools.OleDbConn.State != ConnectionState.Open)
                {
                    CommonTools.OleDbConn.Open();
                }
                OleDbCommand cmd = new OleDbCommand();
                cmd.Connection = CommonTools.OleDbConn;

                cmd.CommandText = "select ID,FuncName,FuncCaption,FuncType,Description,Expression from FormFunc where FuncType='" + FuncType + "'";
                OleDbDataReader reader = cmd.ExecuteReader();
                List<Models.FormFunc> fArr = new List<Models.FormFunc>();
                while (reader.Read())
                {
                    Models.FormFunc f = new Models.FormFunc();
                    f.ID = Convert.ToInt32(reader["ID"].ToString());
                    f.FuncName = reader["FuncName"].ToString();
                    f.FuncCaption = reader["FuncCaption"].ToString();
                    f.FuncType = reader["FuncType"].ToString();
                    f.Description = reader["Description"].ToString();
                    f.Expression = reader["Expression"].ToString();
                    fArr.Add(f);
                }
                ret.Data = fArr;
                CommonTools.OleDbConn.Close();
                ret.Result = true;
            }
            catch (Exception ex)
            {
                if (CommonTools.OleDbConn.State != ConnectionState.Closed)
                {
                    CommonTools.OleDbConn.Close();
                }
                ret.Message = ex.Message;
            }
            return Json(ret);
        }

        private bool createJsFuncFile() {
            string funcStr = "";

            if (CommonTools.OleDbConn.State != ConnectionState.Open)
            {
                CommonTools.OleDbConn.Open();
            }
            OleDbCommand cmd = new OleDbCommand();
            cmd.Connection = CommonTools.OleDbConn;

            cmd.CommandText = "select Expression from FormFunc";
            OleDbDataReader reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                funcStr += reader["Expression"]+"\n";
            }
            CommonTools.OleDbConn.Close();

            string basePath = Server.MapPath("~/js");
            string filePath = basePath + "\\CRFFormFunc.js";
            System.IO.StreamWriter file1 = new System.IO.StreamWriter(filePath, false); //文件已覆盖方式添加内容
            file1.Write(funcStr);  
            file1.Close();                                                                  //关闭文件
            file1.Dispose();
            return true;
        }

        public JsonResult AddFormFunc(string JsonStr){
            DataWrapper ret = new DataWrapper();
            try
            {
                JsonStr = HttpUtility.UrlDecode(JsonStr.Replace("+", "%2B"));
                JavaScriptSerializer jss = new JavaScriptSerializer();
                Models.FormFunc func = jss.Deserialize<Models.FormFunc>(JsonStr);
                if (CommonTools.OleDbConn.State != ConnectionState.Open)
                {
                    CommonTools.OleDbConn.Open();
                }
                //先插
                OleDbCommand cmd = new OleDbCommand();
                cmd.Connection = CommonTools.OleDbConn;

                cmd.CommandText = "insert into FormFunc (FuncName, FuncCaption,FuncType,Description,Expression) values('" + func.FuncName + "', '" + func.FuncCaption + "','" + func.FuncType + "','" + func.Description + "','" + func.Expression + "')";
                cmd.ExecuteNonQuery();

                //后查
                cmd.CommandText = "select top 1 ID, FuncName, FuncCaption,FuncType,Description,Expression from FormFunc order by ID desc";
                OleDbDataReader reader = cmd.ExecuteReader();
                if (reader.Read())
                {
                    Models.FormFunc f = new Models.FormFunc();
                    f.ID = Convert.ToInt32(reader["ID"].ToString());
                    f.FuncName = reader["FuncName"].ToString();
                    f.FuncCaption = reader["FuncCaption"].ToString();
                    f.FuncType = reader["FuncType"].ToString();
                    f.Description = reader["Description"].ToString();
                    f.Expression = reader["Expression"].ToString();
                    
                    ret.Data = f;
                }
                CommonTools.OleDbConn.Close();

                createJsFuncFile();
                ret.Result = true;
            }
            catch (Exception ex)
            {
                if (CommonTools.OleDbConn.State != ConnectionState.Closed)
                {
                    CommonTools.OleDbConn.Close();
                }
                ret.Message = ex.Message;
            }

            return Json(ret);
        }

        public JsonResult AddNewForm(string parFormName)
        {
            DataWrapper ret = new DataWrapper();
            try
            {
                parFormName = HttpUtility.UrlDecode(parFormName);
                if (CommonTools.OleDbConn.State != ConnectionState.Open) {
                    CommonTools.OleDbConn.Open();
                }
                //先插
                OleDbCommand cmd = new OleDbCommand();
                cmd.Connection = CommonTools.OleDbConn;

                cmd.CommandText = "insert into Form (FormName) values('"+parFormName+"')";
                cmd.ExecuteNonQuery();

                //后查
                cmd.CommandText = "select top 1 ID, FormName, IsCreate from Form order by ID desc";
                OleDbDataReader reader = cmd.ExecuteReader();
                if (reader.Read()) {
                    Models.Form f = new Models.Form();
                    f.ID = Convert.ToInt32(reader["ID"].ToString());
                    f.FormName = reader["FormName"].ToString();
                    f.IsCreate = Convert.ToInt32(reader["IsCreate"].ToString());
                    ret.Data = f;
                }
                CommonTools.OleDbConn.Close();
                ret.Result = true;
            }
            catch (Exception ex)
            {
                if (CommonTools.OleDbConn.State != ConnectionState.Closed)
                {
                    CommonTools.OleDbConn.Close();
                }
                ret.Message = ex.Message;
            }

            return Json(ret);

        }

        public JsonResult GetAllForm() {
            DataWrapper ret = new DataWrapper();
            try
            {
                if (CommonTools.OleDbConn.State != ConnectionState.Open)
                {
                    CommonTools.OleDbConn.Open();
                }
                OleDbCommand cmd = new OleDbCommand();
                cmd.Connection = CommonTools.OleDbConn;

                cmd.CommandText = "select ID, FormName, IsCreate from Form order by ID desc";
                OleDbDataReader reader = cmd.ExecuteReader();
                List<Models.Form> fArr = new List<Models.Form>();
                while (reader.Read())
                {
                    Models.Form f = new Models.Form();
                    f.ID = Convert.ToInt32(reader["ID"].ToString());
                    f.FormName = reader["FormName"].ToString();
                    f.IsCreate = Convert.ToInt32(reader["IsCreate"].ToString());
                    fArr.Add(f);
                }
                ret.Data = fArr;
                CommonTools.OleDbConn.Close();
                ret.Result = true;
            }
            catch (Exception ex)
            {
                if (CommonTools.OleDbConn.State != ConnectionState.Closed)
                {
                    CommonTools.OleDbConn.Close();
                }
                ret.Message = ex.Message;
            }

            return Json(ret);
        }
    
        public JsonResult GetFormByID(string parID){
            DataWrapper ret = new DataWrapper();
            try
            {
                if (CommonTools.OleDbConn.State != ConnectionState.Open) {
                    CommonTools.OleDbConn.Open();
                }
                OleDbCommand cmd = new OleDbCommand();
                cmd.Connection = CommonTools.OleDbConn;

                //后查
                cmd.CommandText = "select ID, FormName,IsCreate from Form Where ID =" + parID;
                OleDbDataReader reader = cmd.ExecuteReader();
                if (reader.Read()) {
                    Models.Form f = new Models.Form();
                    f.ID = Convert.ToInt32(reader["ID"].ToString());
                    f.FormName = reader["FormName"].ToString();
                    f.IsCreate = Convert.ToInt32(reader["IsCreate"].ToString());
                    ret.Data = f;
                }
                CommonTools.OleDbConn.Close();
                ret.Result = true;
            }
            catch (Exception ex)
            {
                if (CommonTools.OleDbConn.State != ConnectionState.Closed)
                {
                    CommonTools.OleDbConn.Close();
                }
                ret.Message = ex.Message;
            }
            return Json(ret);
        }

        public JsonResult UpdateFormFunc(string JsonStr)
        {
            DataWrapper ret = new DataWrapper();
            try
            {
                //更新FormFunc数据
                if (CommonTools.OleDbConn.State != ConnectionState.Open)
                {
                    CommonTools.OleDbConn.Open();
                }
                OleDbCommand cmd = new OleDbCommand();
                cmd.Connection = CommonTools.OleDbConn;

                JsonStr = HttpUtility.UrlDecode(JsonStr.Replace("+", "%2B"));
                JavaScriptSerializer jss = new JavaScriptSerializer();
                Models.FormFunc func = jss.Deserialize<Models.FormFunc>(JsonStr);

                cmd.CommandText = "update FormFunc set FuncName = '" + func.FuncName + "', FuncCaption='" + func.FuncCaption + "', FuncType='" + func.FuncType + "', Description='" + func.Description + "', Expression='" + func.Expression + "'  where ID=" + func.ID.ToString();
                cmd.ExecuteNonQuery();
                CommonTools.OleDbConn.Close();

                createJsFuncFile();
                ret.Result = true;
            }
            catch (Exception ex)
            {
                ret.Message = ex.Message;
                if (CommonTools.OleDbConn.State != ConnectionState.Closed)
                {
                    CommonTools.OleDbConn.Close();
                }
            }

            return Json(ret);
        }

        public JsonResult DeleteFormFunc(string JsonStr)
        {
            DataWrapper ret = new DataWrapper();
            try
            {
                //更新FormFunc数据
                if (CommonTools.OleDbConn.State != ConnectionState.Open)
                {
                    CommonTools.OleDbConn.Open();
                }
                OleDbCommand cmd = new OleDbCommand();
                cmd.Connection = CommonTools.OleDbConn;

                JsonStr = HttpUtility.UrlDecode(JsonStr);
                JavaScriptSerializer jss = new JavaScriptSerializer();
                Models.FormFunc func = jss.Deserialize<Models.FormFunc>(JsonStr);

                cmd.CommandText = "delete from FormFunc where ID=" + func.ID.ToString();
                cmd.ExecuteNonQuery();
                CommonTools.OleDbConn.Close();

                ret.Result = true;
            }
            catch (Exception ex)
            {
                ret.Message = ex.Message;
                if (CommonTools.OleDbConn.State != ConnectionState.Closed)
                {
                    CommonTools.OleDbConn.Close();
                }
            }

            return Json(ret);
        }
    }
}
